import bus from './bus'
export default function Dragger(targetId, triggerId, id) {
  this.$target = $(targetId)
  this.$trigger = triggerId ? this.$target.find(triggerId) : this.$target
  this.id = id
  this.handler = {
    move: this.handleMouseMove.bind(this),
    up: this.handleMouseUp.bind(this),
    down: this.handleMouseDown.bind(this)
  }
  $('body').on('mousemove', this.handler.move)
  $('body').on('mouseup', this.handler.up)
  this.$trigger.on('mousedown', this.handler.down)
}
Dragger.prototype = {
  constructor: Dragger,
  ...bus,
  handleMouseMove(e) {
    if (this.$target.data('dragger')) {
      this.move = {
        top: e.clientY - this.mouseStart.top,
        left: e.clientX - this.mouseStart.left
      }
      this.emit('move_' + this.id, {
        move: this.move,
        start: this.start
      })
      // this.$target.css({
      //   top: top > 0 ? top : 0,
      //   left: left > 0 ? left : 0
      // })
    }
  },
  handleMouseUp(e) {
    this.$target.data('dragger', false)
  },
  handleMouseDown(e) {
    this.start = this.$target.offset()
    this.start.top -= $(window).scrollTop()
    this.start.left -= $(window).scrollLeft()
    this.mouseStart = {
      top: e.clientY,
      left: e.clientX
    }
    this.$target.data('dragger', true)
    this.emit('active_' + this.id)
  },
  removeDragger() {
    console.log('off dragger')
    $('body').off('mousemove', this.handler.move)
    $('body').off('mouseup', this.handler.up)
    this.$trigger.off('mousedown', this.handler.down)
  }
}
